package utils

import (
	"encoding/json"
	"fmt"
	"github.com/modern-go/reflect2"
	"reflect"
)

// InterfaceToArray 转换任意interface{}为数组interface{}
func InterfaceToArray(records interface{}) []interface{} {
	// 仅支持切片
	t := reflect.TypeOf(records)

	if t.Kind() != reflect.Slice {
		return []interface{}{records}
	}
	tv := reflect.ValueOf(records)
	var list []interface{}
	for i := 0; i < tv.Len(); i++ {
		list = append(list, tv.Index(i).Interface())
	}
	return list
}

// InterfaceToString 将接口转换为字符串
func InterfaceToString(value interface{}) string {
	//nil则直接返回空
	if reflect2.IsNil(value) {
		return ""
	}

	if d, ok := value.(fmt.Stringer); ok {
		return d.String()
	}

	switch v := value.(type) {
	case string:
		return v
	case int:
		return fmt.Sprintf("%d", v)
	case int8:
		return fmt.Sprintf("%d", v)
	case int16:
		return fmt.Sprintf("%d", v)
	case int32:
		return fmt.Sprintf("%d", v)
	case int64:
		return fmt.Sprintf("%d", v)
	case float32:
		return fmt.Sprintf("%f", value)
	case float64:
		return fmt.Sprintf("%f", value)
	default:
		jsonBytes, err := json.Marshal(v)
		if err != nil {
			return ""
		}
		return string(jsonBytes)
	}

	return ""
}
